import simplejson as json
from dotenv import dotenv_values
from flask import Blueprint, jsonify, request

from applications.common.curd import model_to_dicts
from applications.common.helper import err
from applications.common.utils.http import fail_api, success_api
from applications.extensions import db
from applications.models import Hospital
from applications.models import Record
from applications.schemas import HospitalOutSchema

admin_api = Blueprint('api', __name__, url_prefix='/admin/api')


def verification_api():
    config = dotenv_values('.flaskenv')
    sk = config.get('SECRET_KEY')
    skh = request.headers.get('SECRET-KEY')
    agent = request.headers.get('User-Agent')
    if sk == skh and 'AZYC' in agent:
        return True
    return False


@admin_api.get('/ifOk')
def if_ok():
    res = {
        "msg": "请求成功",
        "code": 0,
        "success": True,
    }
    return jsonify(res)


# 校验提交过来的数据格式
def check_fields(obj, fields):
    keys = list(obj.keys())
    if [False for c in fields if c not in keys]:
        return False
    return True


# 更新预测记录
@admin_api.post('/updateRecord')
def update_record():
    try:
        # 合法性校验
        if verification_api() is False:
            res = {
                "msg": "校验失败",
                "code": 999,
                "success": False,

            }
            return jsonify(res)
        obj = request.get_json()
        data_field = ['name', 'hospital_no', 'username', 'sex', 'id_card', 'case_no', 'device_no', 'cts',
                      'results', 'random', 'test_time', 'create_time', 'dow_count', 'exception', 'states']
        if not check_fields(obj, data_field):
            return fail_api(msg="数据格式不正确")

        h = Hospital.query.filter_by(hospital_no=obj['hospital_no']).first()
        if h != None:
            r = Record.query.filter_by(random=obj['random']).first()
            if r == None:
                add_data = Record(user_id=15,
                                  name=obj['name'],
                                  username=obj['username'],
                                  hospital_no=obj['hospital_no'],
                                  sex=obj['sex'],
                                  type=2,
                                  id_card=obj['id_card'],
                                  case_no=obj['case_no'],
                                  device_no=obj['device_no'],
                                  cts=json.dumps(obj['cts']),
                                  results=obj['results'],
                                  random=obj['random'],
                                  test_time=obj['test_time'],
                                  create_time=obj['create_time'],
                                  dow_count=obj['dow_count'],
                                  exception=obj['exception'],
                                  states=obj['states']
                                  )
                db.session.add(add_data)
                db.session.commit()
        return success_api(msg="提交成功")
    except:
        err()
        return fail_api(msg="提交失败")


# 更新医院
@admin_api.post('/updateHospital')
def update_hospital():
    try:
        # 合法性校验
        if verification_api() is False:
            res = {
                "msg": "校验失败",
                "code": 999,
                "success": False,

            }
            return jsonify(res)
        obj = request.get_json()
        data_field = ['name', 'notes', 'enable', 'create_time', 'hospital_no']
        if not check_fields(obj, data_field):
            return fail_api(msg="数据格式不正确")

        h = Hospital.query.filter_by(hospital_no=obj['hospital_no']).first()
        if h is None:
            #hospital = model_to_dicts(schema=HospitalOutSchema, data=[h])[0]
            add_data = Hospital(name=obj['name'], notes=obj['notes'], user_id=15,
                                hospital_no=obj['hospital_no'], enable=obj['enable'],
                                create_time=obj['create_time'])
            db.session.add(add_data)
            db.session.commit()
        return success_api(msg="提交成功")
    except:
        err()
        return fail_api(msg="提交失败")
